import 'whatwg-fetch';
import Response from './response';
import processHeaders from './processHeaders';
import toQueryString from './util/toQueryString';

/**
 * 用于创建fetch请求
 * @class Request
 * @memberOf kryfe-lib.FetchRequest
 * @inner
 */
export default class Request {
  static instance = new Request();
  /**
   * @constructor
   */
  constructor() {
    ['get', 'post', 'put', 'patch', 'delete', 'head'].forEach((method) => {
      this[method] = (path, { headers = {}, credentials = 'include', mode = 'cors', body = undefined } = {}) => {

        let url = path;
        const fetchConfig: RequestInit = {
          method,
          headers: processHeaders(headers),
          credentials: credentials as RequestCredentials,
          mode: mode as RequestMode,
          body: undefined
        };

        let params = body;
        if (fetchConfig.headers['Content-Type'] !== 'application/json') {
          params = toQueryString(body);
        }

        if (method !== 'get' && method !== 'delete') {
          fetchConfig.body = params;
        } else {
          const paramsString = params ? `${params}&` : '';
          url = `${url}?${paramsString}ui_random=${Date.now()}`;
        }

        return fetch(url, fetchConfig)
          .then((httpResponse) => {
            const ret = Request.preHandleResponse(httpResponse);
            if (ret) {
              throw ret;
            }
            if (httpResponse && httpResponse.ok) {
              return httpResponse.json();
            }
            const { status = -1, statusText = '' } = httpResponse || {};
            throw new Error(`status:${status},statusText:${statusText}`);
          })
          .then((jsonResponse) => {
            const response = new Response(jsonResponse);
            if (response.success) {
              return response;
            }
            throw new Error(`code:${response.code},url:${url}`);
          }).catch((error) => {
            console.warn(JSON.stringify(error));
            throw error;
          });
      };
    });
  }

  /**
  * 预处理fetch请求响应头
  */
  static preHandleResponse(header = {}) {
    return false;
  }

}